﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

namespace Abc.Core;

/// <summary>
/// 邮件发送记录
/// </summary>
public class EmailSendRecordService : IEmailSendRecordService, ITransient
{
    private readonly ILogger<EmailSendRecordService> _logger;
    private readonly ISqlSugarClient _db;
    private readonly ISysCacheService _sysCacheService;
    public EmailSendRecordService(ILogger<EmailSendRecordService> logger
     , ISqlSugarClient db = null,
ISysCacheService sysCacheService = null)
    {
        _logger = logger;
        _db = db;
        _sysCacheService = sysCacheService;
    }
    /// <summary>
    /// 用户注册
    /// </summary>
    /// <returns></returns>
    public async Task<bool> MemberRegister()
    {
        // await SendEmail();
        return false;
    }

    /// <summary>
    /// 用户修改密码
    /// </summary>
    /// <returns></returns>
    public async Task<bool> MemberEditPwd()
    {
        // await SendEmail();
        return false;
    }

    /// <summary>
    /// 用户修改邮箱
    /// </summary>
    /// <returns></returns>
    public async Task<bool> MemberEditEmail()
    {
        // await SendEmail();
        return false;
    }



    /// <summary>
    /// 发送邮件
    /// </summary>
    /// <param name="emailSendTemplateType">邮件模板类型</param>
    /// <param name="dataId">数据ID(订单表id,发票表ID等等)</param>
    /// <param name="sendEmail">发送邮箱</param>
    /// <param name="customerEmail">客户邮箱</param>
    /// <param name="customerNick">客户昵称</param>
    /// <param name="KeyValues">替换关键词字典</param>
    /// <param name="vercode">验证码</param>
    /// <param name="expireTime">过期时间</param>
    /// <returns></returns>
    public async Task<bool> SendEmail(EmailSendTemplateType emailSendTemplateType, int dataId, string sendEmail, string customerEmail, string customerNick, Dictionary<string, string> KeyValues, string vercode = "", DateTimeOffset? expireTime = null)
    {
        var emailSendConfig = await _sysCacheService.GetEmailSendConfig();
        if (emailSendConfig == null || emailSendConfig.IsEnable == false)
        {
            return false;//发件箱不存在或发件箱未开启
        }
        var emailSendTemplate = await _sysCacheService.GetEmailSendTemplate(emailSendTemplateType);



        bool IsSendEmail = false;

        if (string.IsNullOrWhiteSpace(customerEmail))
        {
            return IsSendEmail;
        }

        if (emailSendTemplate != null && emailSendTemplate.IsEnable)
        {
            var emailSend = new SysEmailSendRecord();
            emailSend.SourceDataId = dataId;
            emailSend.TemplateType = emailSendTemplateType;
            emailSend.Subject = RepleseEmailKeyWord(emailSendTemplate.Title, KeyValues);//主题
            emailSend.Content = RepleseEmailKeyWord(emailSendTemplate.Content, KeyValues);
            emailSend.SenderName = emailSendConfig.EmailDisplayName;
            emailSend.SenderEmail = emailSendConfig.EmailAccount;
            emailSend.ReceiveEmail = customerEmail;
            emailSend.ReceiveName = string.IsNullOrWhiteSpace(customerNick) ? customerEmail : customerNick;
            emailSend.SendMaxNum = 1;//默认1次，后面改为配置
            emailSend.VerCode = vercode;//验证码
            emailSend.ExpireTime = expireTime;//过期时间

            //邮件模板附件
            //SetEmailAttathment(emailTemplate, emailSend);

            var result = await _db.InsertRsIdAsync(emailSend);

            IsSendEmail = true;
        }


        return IsSendEmail;
    }



    /// <summary>
    /// 替换关键词
    /// </summary>
    /// <param name="content"></param>
    /// <param name="keyValues"></param>
    /// <returns></returns>
    private string RepleseEmailKeyWord(string content, Dictionary<string, string> keyValues)
    {
        if (string.IsNullOrWhiteSpace(content)) return "";
        if (keyValues == null) keyValues = new Dictionary<string, string>();
        if (!keyValues.ContainsKey("{当前日期}"))
        {
            keyValues.TryAdd("{当前日期}", $"{DateTime.Now:yyyy-MM-dd}");
        }
        if (!keyValues.ContainsKey("{当前日期时间}"))
        {
            keyValues.TryAdd("{当前日期时间}", $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
        }
        foreach (var item in keyValues)
        {
            content = content.Replace(item.Key, item.Value);
        }
        return content;
    }

}